package priv.mill.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

//@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("doGet");
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		
		System.out.println("请求来到");
//		String name = request.getParameter("name");
//		System.out.println(name);
		
//		ServletInputStream inputStream = request.getInputStream();
//		InputStreamReader reader = new InputStreamReader(inputStream);
//		BufferedReader reader2 = new BufferedReader(reader);
//		String line;
//		while((line=reader2.readLine())!=null){
//			System.out.println(line);
//			
//		}
		
		
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(500*1024);
		File file = new File(System.getProperty("java.io.tmpdir"));
		factory.setRepository(file);
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("utf-8");
		upload.setFileSizeMax(1024*1024);
		upload.setSizeMax(1024*1024*3);
		
		try {
			List<FileItem> list = upload.parseRequest(request);
			for (FileItem item : list) {
				if(item.isFormField()){
					String fieldName = item.getFieldName();
					String string = item.getString();
					System.out.println(fieldName+"---"+string);
				}else{
					String fieldName = item.getFieldName();
					String path = request.getServletContext().getRealPath(fieldName);
					System.out.println(path);
					
					item.write(new File(path));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	public static void main(String[] args) {
		Properties properties = System.getProperties();
		properties.list(System.out);
	}

}
